<template>
  <div class="login-container">
    <van-nav-bar title="标题" left-arrow @click-left="$router.go(-1)" />
    <van-form @submit="onSubmit">
      <van-field
        v-model="mobile"
        name="mobile"
        label="用户名"
        placeholder="用户名"
        :rules="[
          { required: true, message: '请填写用户名' },
          {
            pattern: /^(13[0-9]|14[01456879]|15[0-35-9]|16[2567]|17[0-8]|18[0-9]|19[0-35-9])\d{8}$/,
            message: '请填写用户名'
          }
        ]"
      />
      <van-field
        v-model="code"
        type="text"
        name="code"
        label="验证码"
        placeholder="密码"
        :rules="[
          { required: true, message: '请填写密码' },
          { pattern: /^\d{6}$/, message: '验证码格式不对' }
        ]"
      />
      <div style="margin: 16px;">
        <van-button
          round
          block
          :loading="isDisabled"
          :disabled="isDisabled"
          type="info"
          native-type="submit"
          loading-text="加载中..."
          >提交</van-button
        >
      </div>
    </van-form>
  </div>
</template>

<script>
import { userLogin } from './login.js'
import { setToken } from '@/utils/token.js'
export default {
  name: 'login',
  data () {
    return {
      mobile: '15112345678',
      code: '246810',
      // 控制禁止按钮
      isDisabled: false
    }
  },
  methods: {
    onSubmit (values) {
      this.isDisabled = true
      userLogin(values)
        .then(res => {
          // console.log(res)
          this.$toast.success('登入成功')

          // 设置token
          setToken(res.data.data)
          this.$router.push({ path: '/home' })
        })
        .catch(err => {
          this.$toast.fail('登入失败')
        })
        .then(() => {
          this.isDisabled = false
        })
    }
  }
}
</script>

<style lang="less">
.login-container {
  .van-nav-bar__content {
    background: rgb(25, 137, 250);
    .van-icon-arrow-left {
      color: #fff;
    }
  }

  .van-nav-bar__title {
    color: #fff;
  }
}
</style>
